﻿using HlElock.Api.Models;
using HlELock.Core;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace HlElock.Api
{
    public class RoomApiClient
    {
        private readonly HttpClient _httpClient;

        public RoomApiClient(HttpClient httpClient)
        {
            _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
            _httpClient.BaseAddress = new Uri("http://pms.njxly.xyz");
        }


        /// <summary>
        /// 添加房间 (使用 RoomInfo 对象封装参数)
        /// </summary>
        /// <param name="roomInfo">包含房间详细信息的对象</param>
        /// <returns>添加成功返回 true，否则返回 false。</returns>
        public async Task<bool> AddRoomAsync(RoomInfo roomInfo)
        {
            if (roomInfo == null)
            {
                throw new ArgumentNullException(nameof(roomInfo));
            }
            roomInfo.OperId = MyAppContext.CurrentUser.Account;
            roomInfo.PrjCode = MyAppContext.HotelInfo.HotelCode;
            // 使用 using 确保 MultipartFormDataContent 被正确释放
            var formData = new MultipartFormDataContent
                 {
                     // 将 RoomInfo 对象的属性添加到表单数据中
                     // 注意：StringContent 的第二个参数是字段名，必须与 API 期望的字段名匹配
                     { new StringContent(roomInfo.FlType), "fltype" },
                     { new StringContent(roomInfo.TjDate), "tjdate" },
                     { new StringContent(roomInfo.ExtNum), "extnum" },
                     { new StringContent(roomInfo.OperId), "operid" },
                     { new StringContent(roomInfo.Floor), "floor" },
                     { new StringContent(roomInfo.Build), "build" },
                     { new StringContent(roomInfo.Window), "window" },
                     { new StringContent(roomInfo.PrjCode), "prjcode" },
                     { new StringContent(roomInfo.RoomId), "roomid" },
                     { new StringContent(roomInfo.Face), "face" },
                     { new StringContent(roomInfo.PreId), "preid" },
                     { new StringContent(roomInfo.SufId), "sufid" }
                 };

            var requestUri = "/tp/public/Pmsroomadd";

            try
            {
                var response = await _httpClient.PostAsync(requestUri, formData);

                // 可选：记录请求和响应详情用于调试
                // Console.WriteLine($"请求 URL: {requestUri}");
                // Console.WriteLine($"发送的数据: {string.Join(", ", ...)}"); // 需要额外处理才能打印 formData 内容

                var result = await ReadResponseContentAsync(response);
                if (result.IsSuccess)
                    return true;
                else
                    throw new Exception(result.Message);
            }
            catch (HttpRequestException httpEx)
            {
                // 记录更详细的错误信息
                Console.WriteLine($"请求失败 (HTTP {httpEx.HResult}): {httpEx.Message}");
                // 可以考虑抛出自定义异常或返回带有更多信息的结果对象
                return false;
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                formData.Dispose();
            }
        }

        private async Task<ApiResponse> ReadResponseContentAsync(HttpResponseMessage response)
        {
            response.EnsureSuccessStatusCode();

            var responseBody = await response.Content.ReadAsStringAsync();


            // 尝试将 JSON 响应反序列化为 RoomInfo 数组
            var result = JsonConvert.DeserializeObject<ApiResponse>(responseBody);
            return result;
        }


        private async Task<ApiResponse<T>> ReadResponseContentAsync<T>(HttpResponseMessage response)
        {
            response.EnsureSuccessStatusCode();

            var responseBody = await response.Content.ReadAsStringAsync();


            // 尝试将 JSON 响应反序列化为 RoomInfo 数组
            var result = JsonConvert.DeserializeObject<ApiResponse<T>>(responseBody);
            return result;
        }

        /// <summary>
        /// 删除房间 (使用 DeleteRoomRequest 对象封装参数)
        /// </summary>
        /// <returns>返回删除结果</returns>
        public async Task<bool> DeleteRoomAsync(DeleteRoomRequest deleteRequest)
        {
            if (deleteRequest == null)
            {
                throw new ArgumentNullException(nameof(deleteRequest));
            }

            // 使用 using 确保 MultipartFormDataContent 被正确释放
            var formData = new MultipartFormDataContent();

            // 将 DeleteRoomRequest 对象的属性添加到表单数据中
            // 字段名必须与 API 期望的完全一致
            formData.Add(new StringContent(deleteRequest.Build), "build");
            formData.Add(new StringContent(deleteRequest.Floor), "floor");
            formData.Add(new StringContent(deleteRequest.RoomId), "roomid");
            formData.Add(new StringContent(deleteRequest.PrjCode), "prjcode");
            formData.Add(new StringContent(deleteRequest.OperId), "operid");
            formData.Add(new StringContent(deleteRequest.TjDate), "tjdate");

            var requestUri = "/tp/public/Pmsroomdel";

            try
            {
                var response = await _httpClient.PostAsync(requestUri, formData);

                // 检查响应是否成功
                response.EnsureSuccessStatusCode();

                var responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"房间删除成功: {response.StatusCode}, 响应内容: {responseBody}");

                return true;
            }
            catch (HttpRequestException httpEx)
            {
                Console.WriteLine($"删除房间失败 (HTTP {httpEx.HResult}): {httpEx.Message}");
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除房间时发生错误: {ex.Message}");
                return false;
            }
            finally
            {
                formData.Dispose();
            }
        }


        /// <summary>
        /// 修改 PMS 系统中的房间信息。
        /// </summary>
        /// <param name="editRequest">一个包含修改房间所需参数的对象。</param>
        /// <returns>如果修改成功（收到成功状态码）则返回 true；否则返回 false。</returns>
        public async Task<bool> EditRoomAsync(EditRoomRequest editRequest)
        {
            if (editRequest == null)
            {
                throw new ArgumentNullException(nameof(editRequest));
            }

            // 使用 using 确保 MultipartFormDataContent 被正确释放
            var formData = new MultipartFormDataContent();

            // 将 EditRoomRequest 对象的属性添加到表单数据中
            // 字段名必须与 API 期望的完全一致
            formData.Add(new StringContent(editRequest.FlType), "fltype");
            formData.Add(new StringContent(editRequest.Reason), "reason");
            formData.Add(new StringContent(editRequest.TjDate), "tjdate");
            formData.Add(new StringContent(editRequest.ExtNum), "extnum");
            formData.Add(new StringContent(editRequest.OperId), "operid");
            formData.Add(new StringContent(editRequest.Floor), "floor");
            formData.Add(new StringContent(editRequest.Build), "build");
            formData.Add(new StringContent(editRequest.Window), "window");
            formData.Add(new StringContent(editRequest.PrjCode), "prjcode");
            formData.Add(new StringContent(editRequest.RoomId), "roomid");
            formData.Add(new StringContent(editRequest.Tag), "tag");
            formData.Add(new StringContent(editRequest.Face), "face");
            formData.Add(new StringContent(editRequest.PreId), "preid");
            formData.Add(new StringContent(editRequest.SufId), "sufid");

            var requestUri = "/tp/public/Pmsroomedit "; // 注意 URL 末尾可能有空格

            try
            {
                var response = await _httpClient.PostAsync(requestUri, formData);

                // 检查响应是否成功
                response.EnsureSuccessStatusCode();

                var responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"房间修改成功: {response.StatusCode}, 响应内容: {responseBody}");

                return true;
            }
            catch (HttpRequestException httpEx)
            {
                Console.WriteLine($"修改房间失败 (HTTP {httpEx.HResult}): {httpEx.Message}");
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"修改房间时发生错误: {ex.Message}");
                return false;
            }
            finally
            {
                formData.Dispose();
            }
        }

        /// <summary>
        /// 查询 PMS 系统中的房间信息。
        /// </summary>
        /// <param name="queryRequest">一个包含查询房间所需参数的对象。</param>
        /// <returns>如果查询成功，则返回包含房间信息的列表；否则返回 null。</returns>
        public async Task<RoomInfo[]> QueryRoomsAsync(QueryRoomRequest queryRequest)
        {
            if (queryRequest == null)
            {
                throw new ArgumentNullException(nameof(queryRequest));
            }
            queryRequest.PrjCode = MyAppContext.HotelInfo.HotelCode;
            // 使用 using 确保 MultipartFormDataContent 被正确释放
            var formData = new MultipartFormDataContent();

            // 将 QueryRoomRequest 对象的属性添加到表单数据中
            if (!string.IsNullOrWhiteSpace(queryRequest.Build))
                formData.Add(new StringContent(queryRequest.Build), "build");
            if (!string.IsNullOrWhiteSpace(queryRequest.Floor))
                formData.Add(new StringContent(queryRequest.Floor), "floor");
            if (!string.IsNullOrWhiteSpace(queryRequest.RoomId))
                formData.Add(new StringContent(queryRequest.RoomId), "roomid");
            if (!string.IsNullOrWhiteSpace(queryRequest.PrjCode))
                formData.Add(new StringContent(queryRequest.PrjCode), "prjcode");
            if (!string.IsNullOrWhiteSpace(queryRequest.OperId))
                formData.Add(new StringContent(queryRequest.OperId), "operid");
            if (!string.IsNullOrWhiteSpace(queryRequest.TjDate))
                formData.Add(new StringContent(queryRequest.TjDate), "tjdate");

            var requestUri = "/tp/public/Pmsroomquery";

            try
            {
                var response = await _httpClient.PostAsync(requestUri, formData);

                response.EnsureSuccessStatusCode();

                var responseBody = await response.Content.ReadAsStringAsync();


                // 尝试将 JSON 响应反序列化为 RoomInfo 数组
                var rooms = JsonConvert.DeserializeObject<ApiResponse<RoomInfo[]>>(responseBody);

                if (rooms.IsSuccess)
                {
                    return rooms.Data;
                }
                else
                {
                    throw new Exception(rooms.Message);
                }
            }
            catch (HttpRequestException httpEx)
            {
                Console.WriteLine($"查询房间失败 (HTTP {httpEx.HResult}): {httpEx.Message}");
                return null; // 返回 null 表示失败
            }
            catch (JsonException jsonEx)
            {
                Console.WriteLine($"解析查询响应 JSON 失败: {jsonEx.Message}");
                return null; // 返回 null 表示失败
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询房间时发生错误: {ex.Message}");
                throw;
            }
            finally
            {
                formData.Dispose();
            }
        }

    }
}